// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: jhkim

#pragma once

#include <iostream>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <string>
#include <vector>

#include <boost/date_time/posix_time/posix_time.hpp>

#include "coin2/exchange/apollox_futures/symbology/currency.h"
#include "coin2/exchange/base/symbology/derivative_util.h"
#include "coin2/exchange/base/symbology/futures_product.h"

namespace coin2::exchange::apollox_futures::symbology {

using coin2::exchange::apollox_futures::symbology::ApolloxFuturesCurrency;

class ApolloxFuturesProduct
    : public base::symbology::FuturesProduct<ApolloxFuturesCurrency, ApolloxFuturesProduct>,
      public base::symbology::ProductFromStrMixin<ApolloxFuturesProduct> {
 public:
  using FuturesProduct =
      base::symbology::FuturesProduct<ApolloxFuturesCurrency, ApolloxFuturesProduct>;
  using ContractType = base::symbology::ContractType;

 public:
  ApolloxFuturesProduct(
      const ApolloxFuturesCurrency& base,
      const ApolloxFuturesCurrency& quote,
      const std::string& native_product,
      const std::string& native_subscription_symbol,
      const ContractType contract_type,
      const int64_t expiry_timestamp,
      const int64_t resolve_timestamp)
      : FuturesProduct(
            base,
            quote,
            native_product,
            StringToLowerCopy(native_subscription_symbol),
            base::market::ExchangeType::Apollox,
            contract_type,
            expiry_timestamp,
            resolve_timestamp) {}

 public:
  static std::unique_ptr<ApolloxFuturesProduct> FromNativeStrImpl(
      const std::string& native_product,
      const int64_t resolve_timestamp) {
    using base::symbology::IsDateStr;
    std::string quote_str = "USDT";
    std::string base_str = native_product.substr(0, 3);
    std::string expiry_str = "PERPETUAL";

    std::vector<std::string> splitted;
    splitted = Split(native_product, "_");
    if (splitted.size() == 1) {
      // USDT or BUSD perpetual case
      using std::string_literals::operator""s;
      for (const std::string& quote_cand : {"USDT"s, "BUSD"s}) {
        if (StringEndsWith(native_product, quote_cand)) {
          quote_str = quote_cand;
          break;
        }
      }
      CHECK_GT(quote_str.length(), 0) << native_product;
      CHECK_EQ(
          native_product.substr(native_product.length() - quote_str.length(), quote_str.length()),
          quote_str)
          << native_product;
      base_str = native_product.substr(0, native_product.length() - quote_str.length());
    } else if (splitted.size() == 2) {
      expiry_str = splitted[1];
      if (expiry_str == "PERP") {
        expiry_str = "PERPETUAL";
      }

      auto native_product_str = splitted[0];
      if ("USDT" == native_product_str.substr(native_product_str.length() - 4, 4)) {
        quote_str = "USDT";
      } else if ("USD" == native_product_str.substr(native_product_str.length() - 3, 3)) {
        quote_str = "USD";
      } else {
        NOTREACHED() << native_product;
      }
      base_str = native_product_str.substr(0, native_product_str.length() - quote_str.length());
    } else {
      return {};
    }

    const auto quote = ApolloxFuturesCurrency::FromNativeStrNoThrow(quote_str, resolve_timestamp);
    const auto base = ApolloxFuturesCurrency::FromNativeStrNoThrow(base_str, resolve_timestamp);
    if (!base) {
      return {};
    }

    std::string native_product_tmp;
    std::string native_subscription_symbol;
    ContractType contract_type;
    int64_t expiry_timestamp;
    bool success = CalculateParams(
        *base,
        *quote,
        expiry_str,
        resolve_timestamp,
        &native_product_tmp,
        &native_subscription_symbol,
        &contract_type,
        &expiry_timestamp);
    if (success) {
      if (IsDateStr(expiry_str)) {
        DCHECK_EQ(native_product_tmp, native_product);
      }
      return std::make_unique<ApolloxFuturesProduct>(
          *base,
          *quote,
          native_product,
          native_subscription_symbol,
          contract_type,
          expiry_timestamp,
          resolve_timestamp);
    } else {
      return {};
    }
  }

  static bool CalculateParams(
      const ApolloxFuturesCurrency& base,
      const ApolloxFuturesCurrency& quote,
      const std::string& expiry_str,
      const int64_t resolve_timestamp,
      std::string* native_product,
      std::string* native_subscription_symbol,
      ContractType* contract_type,
      int64_t* expiry_timestamp) {
    using base::symbology::ContractType;
    using base::symbology::ExchangeType;
    using base::symbology::FindExpiryFriday;
    using base::symbology::IsDateStr;
    using base::symbology::StringToContractType;
    using base::symbology::ToDateStr;

    static const int64_t expiry_time_of_day_nanosec = 8 * 3600 * 1e9;
    std::stringstream ss;

    // native_product
    ss.str(std::string());
    if (std::all_of(std::begin(expiry_str), std::end(expiry_str), ::isdigit)) {
      bool found = false;
      for (auto type : {ContractType::QUARTER, ContractType::NEXT_QUARTER}) {
        auto timestamp = FindExpiryFriday(
            ExchangeType::Apollox,
            type,
            resolve_timestamp,
            expiry_time_of_day_nanosec);
        if (expiry_str == ToDateStr(timestamp) || expiry_str == ToDateStr(timestamp).substr(2)) {
          *contract_type = type;
          *expiry_timestamp = timestamp;
          ss << base.native_currency() << quote.native_currency() << '_'
             << ToDateStr(*expiry_timestamp).substr(2);
          found = true;
          break;
        }
      }
      if (!found) {
        return false;
      }
    } else {
      auto type = StringToContractType(expiry_str);
      if (type) {
        *contract_type = type.value();
        if (*contract_type == ContractType::PERPETUAL) {
          *expiry_timestamp = FuturesProduct::PERPETUAL_TIMESTAMP;
          if (quote.native_currency() == "USDT" || quote.native_currency() == "BUSD") {
            ss << base.native_currency() << quote.native_currency();
          } else if (quote.native_currency() == "USD") {
            ss << base.native_currency() << quote.native_currency() << "_PERP";
          } else {
            return false;
          }
        } else {
          *expiry_timestamp = FindExpiryFriday(
              ExchangeType::Apollox,
              *contract_type,
              resolve_timestamp,
              expiry_time_of_day_nanosec);
          ss << base.native_currency() << quote.native_currency() << '_'
             << ToDateStr(*expiry_timestamp).substr(2);
        }
      } else {
        return false;
      }
    }
    *native_product = ss.str();
    *native_subscription_symbol = *native_product;
    return true;
  }
};

}  // namespace coin2::exchange::apollox_futures::symbology
